import json
import threading
import time

import requests


def printf(s):
    print('[%s][%s]%s' % (threading.current_thread().getName(), time.strftime("%X"), s))


def login():
    headers = {
        'Origin': 'http://center.beyonds.com',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,ja;q=0.6',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
        'Content-Type': 'application/json;charset=UTF-8',
        'Accept': 'application/json, text/plain, */*',
        'Referer': 'http://center.beyonds.com/',
        'Connection': 'keep-alive',
    }
    data = '{"userName":"adminhmq","password":"8389900da0fc05a267c5fde6f33fe911","channel":0,"type":0}'
    response = requests.post('http://center.beyonds.com/permission/voyager/basisb/v1/user/login', headers=headers,
                             data=data)
    print(response.text)


def members(place_id, index, size):
    headers = {
        'orgname': '%E5%91%BC%E5%B8%82%E5%9B%9E%E6%B0%91%E5%8C%BA%E4%B8%87%E8%BE%BE%E5%B9%BF%E5%9C%BA',
        'Accept-Encoding': 'gzip, deflate',
        'plazaCode': '1104483',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,ja;q=0.6',
        'orgTypeName': '%E5%B9%BF%E5%9C%BA',
        'userid': '259300419157991424',
        'orgcode': '1104483',
        'orgTypeCode': '10003',
        'Connection': 'keep-alive',
        'workingOrgCode': '1104483',
        'areaCode': '10018',
        'groupCode': '101',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
        'tenantId': '2018092600001',
        'Accept': 'application/json, text/plain, */*',
        'username': '%E5%9B%9E%E6%B0%91%E5%8C%BA%E4%B8%87%E8%BE%BE%E5%B9%BF%E5%9C%BA%E7%AE%A1%E7%90%86%E5%91%98',
        'storeCode': '',
        'Referer': 'http://center.beyonds.com/',
        'centerCode': '1008',
        'token': 'Mjc0NDY2MTYwNzU3NDQ4NzA0',
    }

    params = (
        ('scope', place_id),
        ('scopeType', '10003'),
        ('mobileNo', ''),
        ('memberCardCode', ''),
        ('memberCode', ''),
        ('regStartTime', '2018-12-14'),
        ('regEndTime', '2018-12-15'),
        ('expandingChannel', ''),
        ('fromOrgId', ''),
        ('certificateType', ''),
        ('certificateCode', ''),
        ('sex', ''),
        ('name', ''),
        ('activated', ''),
        ('status', ''),
        ('refereeUser', ''),
        ('pageIndex', index),
        ('pageSize', size),
        ('timestr', time.time()),
    )

    response = requests.get('http://center.beyonds.com/member/members', headers=headers, params=params)
    # print(response.text)
    return response.text


def writeSql(s):
    f = open("sql/%s.sql" % file_name, "a")
    f.write('%s\n' % s.strip())
    f.close()


def deal(placeId, index, size):
    while True:
        printf("进行第%s页" % index)
        result = members(placeId, index, size)
        r = json.loads(result)
        if r["status"] != 200:
            break
        sql = "insert into wanda_user(`member_id`,`phone`,`activated`,`place_id`,`reg_date`) values "
        items = r["data"]["items"]
        item_size = len(items)
        if item_size == 0:
            break
        for i in range(0, item_size):
            member_id = items[i]["id"]
            phone = items[i]["mobile"]
            activated = items[i]["activated"]
            place_id = items[i]["fromOrgId"]
            place_name = items[i]["fromOrg"]
            reg_data = items[i]["regDate"]
            if i == (item_size - 1):
                p = "('%s','%s',%s,'%s',%s);" % (member_id, phone, activated, place_id, reg_data)
            else:
                p = "('%s','%s',%s,'%s',%s)," % (member_id, phone, activated, place_id, reg_data)
            sql += p
        writeSql(sql)
        printf("完成第%s页" % index)
        if item_size != size:
            print("最后一页%s条" % item_size)
            break
        index += 1
        # if index == 867:
        #     break
        # time.sleep(1)


if __name__ == '__main__':
    f = open("undone.data", "r")
    while True:
        mystr = f.readline()
        if not mystr:
            break
        r = mystr.split(" ")
        print(r)
        global place_id
        place_id = r[0]
        global file_name
        file_name = "auto0203-%s" % place_id
        index = 1
        size = 200
        printf("进行%s" % place_id)
        deal(place_id, index, size)
